import 'package:flutter/material.dart';
import '../models/note.dart';
import '../models/folder.dart';
import 'package:uuid/uuid.dart';
import '../pages/note_edit_page.dart';
import '../service/database_service.dart';

class FolderPage extends StatefulWidget {
  const FolderPage({super.key});

  @override
  State<FolderPage> createState() => _FolderPageState();
}

class _FolderPageState extends State<FolderPage> {
  final List<Folder> _folders = []; 
  final DatabaseService _databaseService = DatabaseService(); 
  final Map<String, List<Note>> notesMap = {}; 
  bool _isLoading = true; 
  String noneFolderId = "-1111"; 

  @override
  void initState() {
    super.initState();
    _loadFolders(); 
  }

  Future<void> _loadFolders() async {
    try {
      final folders = await _databaseService.getAllFolders();
      final notes = await _databaseService.getAllNotes();
      for (var note in notes) {
        var folderId = note.folderId;
        if (folderId == null || folderId.isEmpty) {
          var list = notesMap[noneFolderId] ?? [];
          list.add(note);
          notesMap[noneFolderId] = list;
          continue;
        }
        var list = notesMap[folderId] ?? [];
        list.add(note);
        notesMap[folderId] = list;
      }
      setState(() {
         _folders.clear();
        _folders.addAll(folders);
        if (notesMap[noneFolderId] != null) {
          _folders.add(
            Folder(
              id: noneFolderId,
              name: '其他',
              createdAt: DateTime.now(),
              updatedAt: DateTime.now(),
            ),
          );
        }
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _createFolder() async {
    final nameController = TextEditingController();

    final result = await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('新建文件夹'),
        content: TextField(
          controller: nameController,
          maxLength: 10,
          decoration: const InputDecoration(
            hintText: '请输入文件夹名称',
            counterText: '',
            border: OutlineInputBorder(),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              if (nameController.text.isNotEmpty) {
                Navigator.pop(context, nameController.text);
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('文件夹名称不能为空')),
                );
              }
            },
            child: const Text('添加'),
          ),
        ],
      ),
    );

    if (result != null) {
      try {
        final folder = Folder(
          id: const Uuid().v4(),
          name: result,
          createdAt: DateTime.now(),
          updatedAt: DateTime.now(),
        );
        await _databaseService.insertFolder(folder);
        setState(() {
          _folders.insert(0, folder);
        });
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('创建文件夹失败: $e')),
          );
        }
      }
    }
  }

  Future<void> _editFolder(Folder folder) async {
    final nameController = TextEditingController(text: folder.name);

    final result = await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('编辑文件夹'),
        content: TextField(
          controller: nameController,
          maxLength: 10,
          decoration: const InputDecoration(
            hintText: '请输入文件夹名称',
            counterText: '',
            border: OutlineInputBorder(),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              if (nameController.text.isNotEmpty) {
                Navigator.pop(context, nameController.text);
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('文件夹名称不能为空')),
                );
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );

    if (result != null) {
      try {
        final updatedFolder = folder.copyWith(
          name: result,
          updatedAt: DateTime.now(),
        );
        await _databaseService.updateFolder(updatedFolder);
        setState(() {
          _folders[_folders.indexOf(folder)] = updatedFolder;
        });
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('更新文件夹失败: $e')),
          );
        }
      }
    }
  }

  Future<void> _showDeleteDialog(Folder folder) async {
    final result = await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除文件夹'),
        content: const Text('确定要删除这个文件夹吗？文件夹中的所有笔记也会被删除。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );

    if (result == true) {
      try {
        await _databaseService.deleteFolder(folder.id);
        setState(() {
          _folders.removeWhere((f) => f.id == folder.id);
        });
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('删除文件夹失败: $e')),
          );
        }
      }
    }
  }

  void _showPasswordInputDialog(BuildContext context, Function(String text) onPasswordEntered) {
    final TextEditingController passwordController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('请输入密码'),
        content: TextField(
          controller: passwordController,
          obscureText: true,
          decoration: const InputDecoration(hintText: '输入密码'),
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context); 
            },
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              String password = passwordController.text;
              if (password.isNotEmpty) {
                Navigator.pop(context); 
                onPasswordEntered(password);
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('密码不能为空')),
                );
              }
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        titleSpacing: 0,
        title: const Text('我的文件夹', style: TextStyle(fontWeight: FontWeight.bold),),
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: _createFolder,
          ),
        ],
      ),
      body: _isLoading 
          ? const Center(child: CircularProgressIndicator())
          : _folders.isEmpty
              ? const Center(
                  child: Text('暂无文件夹，点击右上角创建'),
                )
              : ListView.builder(
                  itemCount: _folders.length,
                  itemBuilder: (context, index) {
                    final folder = _folders[index];
                    return Container(
                      margin: const EdgeInsets.only(left: 8, right: 8, bottom: 8),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Column(
                        children: [
                          ListTile(
                            leading: const Icon(Icons.folder, color: Colors.yellow,), 
                            title: Text(folder.name), 
                            trailing: folder.id == noneFolderId
                                ? null
                                : Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      IconButton(
                                        icon: const Icon(Icons.edit),
                                        onPressed: () => _editFolder(folder),
                                      ),
                                      IconButton(
                                        icon: const Icon(Icons.delete),
                                        onPressed: () =>
                                            _showDeleteDialog(folder),
                                      ),
                                    ],
                                  ),
                          ),
                          ListView.builder(
                            padding: EdgeInsets.zero,
                            itemCount: notesMap[folder.id] == null
                                ? 0
                                : notesMap[folder.id]!.length,
                            shrinkWrap: true,
                            itemBuilder: (context, index) {
                              var note = notesMap[folder.id]![index];
                              return Card(
                                margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                                child: ListTile(
                                  contentPadding: const EdgeInsets.only(left: 8, right: 16),
                                  horizontalTitleGap: 8,
                                  leading: note.isPinned
                                      ? Icon(Icons.publish, color: Colors.blue.shade400)
                                      : null,
                                  title: Text(
                                    note.title.isEmpty ? '无标题' : note.title,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  subtitle: Text(
                                    note.password?.isNotEmpty != true
                                        ? note.content
                                        : "******",
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  trailing: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      Text(
                                        '${note.updatedAt.month}/${note.updatedAt.day} ${note.updatedAt.hour}:${note.updatedAt.minute.toString().padLeft(2, '0')}',
                                        style: const TextStyle(fontSize: 12),
                                      ),
                                      if( note.label?.isNotEmpty == true ) Container(
                                        margin: const EdgeInsets.only(top: 4),
                                        padding: const EdgeInsets.symmetric(
                                            horizontal: 12, vertical: 4),
                                        decoration: BoxDecoration(
                                          color: Colors.blue.shade100,
                                          borderRadius: BorderRadius.circular(12),
                                        ),
                                        child: Text(
                                          note.label ?? '',
                                          style: const TextStyle(fontSize: 12),
                                        ),
                                      )
                                    ],
                                  ),
                                  onTap: () async {
                                    if (note.password?.isNotEmpty == true) {
                                      _showPasswordInputDialog(context, (text) async {
                                        if (note.password == text) {
                                          final updatedNote = await Navigator.push<Note>(
                                            context,
                                            MaterialPageRoute(
                                              builder: (context) => NoteEditPage(note: note),
                                            ),
                                          );
                                          if (updatedNote != null) {
                                            setState(() {notesMap[folder.id]![index] = updatedNote;});
                                          }
                                        } else {
                                          ScaffoldMessenger.of(context).showSnackBar(
                                            const SnackBar(content: Text('密码错误')),
                                          );
                                        }
                                      });
                                    } else {
                                      final updatedNote = await Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) => NoteEditPage(note: note),
                                        ),
                                      );
                                      if (updatedNote != null) {
                                        setState(() {notesMap[folder.id]![index] = updatedNote;});
                                      }
                                    }
                                  },
                                ),
                              );
                            },
                          )
                        ],
                      ),
                    );
                  },
                ),
    );
  }
}
